package org.contextsensitivetodo.todoview;

import java.util.ArrayList;

import org.contextsensitivetodo.CSTodoApplication;
import org.contextsensitivetodo.R;
import org.contextsensitivetodo.todoview.adapter.ToDoListAdapter;
import org.contextsensitivetodo.todoview.model.TodoItem;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class ToDoViewActivity extends ListActivity {

	
	private Button addButton;
	private CSTodoApplication app;
	private ToDoListAdapter adapter;
	private Button removeButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.todoviewmain);
		setUpViews();
		
		app = getCSTodoApplication();
		adapter = new ToDoListAdapter(app.getCurrentToDos(), this);
		setListAdapter(adapter);
		
	}

	
	@Override
	protected void onResume() {
		super.onResume();
		adapter.forceReload();
		
	}


	private void setUpViews() {
		addButton = (Button)findViewById(R.id.AddToDoItemButton);
		addButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(ToDoViewActivity.this, AddToDoActivity.class);
				startActivity(intent);
			}
		});
		
		
		removeButton = (Button)findViewById(R.id.RemoveToDoItemButton);
		removeButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				removeCompletedTasks();
			}
		});
	}
	
	
	protected void removeCompletedTasks() {
		Long[] ids = adapter.removeCompletedTasks();
		app.deleteTodos(ids);
		
		
	}


	protected CSTodoApplication getCSTodoApplication() {
		CSTodoApplication app = (CSTodoApplication) getApplication();
		return app;
		
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		adapter.toggleTaskCompleteAtPosition(position);
		TodoItem item = adapter.getItem(position);
		app.saveTodo(item);
		
	}

}
